package com.tang.campus_market.filter;


import com.tang.campus_market.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter(filterName = "LoginFilter",urlPatterns =  //{"/user/in/*"}
            {"/666/666/*","/user/preInfo"}
        )
public class LoginFilter implements Filter {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;

        //判断是否已登录
        User user = (User) req.getSession().getAttribute("user");
        if(user==null){
            res.sendRedirect(req.getContextPath()+"/user/loginError");
            return;
        }else {
            req.getSession().setMaxInactiveInterval(60*60*2);
        }

        //判断是否重复登录
        String sessionId = (String) redisTemplate.opsForValue().get(user.getEmail());
        if (!sessionId.equals(req.getSession().getId())){
            res.sendRedirect(req.getContextPath()+"/user/repeatLogin");
            return;
        }else {
            req.getSession().setMaxInactiveInterval(60*60*2);
        }


        filterChain.doFilter(req,res);

    }

    @Override
    public void destroy() {

    }
}
